package com.taotao.search.service.impl;

import com.taotao.common.pojo.SearchItem;
import com.taotao.common.pojo.SearchResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.search.dao.SearchDao;
import com.taotao.search.mapper.SearchItemMapper;
import com.taotao.search.service.SearchService;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private SearchItemMapper mapper;
    @Autowired
    private SolrServer solrServer;
    @Autowired
    private SearchDao searchDao;

    @Override
    public TaotaoResult importAllItems() throws Exception{
        List<SearchItem> itemList = mapper.getSearchItemList();
        for (SearchItem searchItem : itemList) {
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", searchItem.getId().toString());
            document.addField("item_title", searchItem.getTitle());
            document.addField("item_sell_point", searchItem.getSell_point());
            document.addField("item_price", searchItem.getPrice());
            document.addField("item_image", searchItem.getImage());
            document.addField("item_category_name", searchItem.getCategory_name());
            document.addField("item_desc", searchItem.getItem_desc());

            solrServer.add(document);
        }
        solrServer.commit();
        return TaotaoResult.ok();
    }

    @Override
    public SearchResult search(String queryString, Integer page, Integer rows) throws Exception {
        //创建solrquery对象
        //设置主查询条件，过滤条件
        //调用dao的方法，返回searchResult
        //设置searchResult的总页数
        //返回
        //设置查询条件
        SolrQuery query = new SolrQuery();
        if (!StringUtils.isEmpty(queryString)) {
            query.setQuery(queryString);
        } else {
            query.setQuery("*:*");
        }
        //设置分页
        query.setStart((page-1)*rows);
        query.setRows(rows);
        //设置默认搜索域
        query.set("df", "item_keywords");
        //设置高亮
        query.setHighlight(true);
        query.setHighlightSimplePre("<em style=\"color:red\">");
        query.setHighlightSimplePost("</em>");
        //设置高亮域
        query.addHighlightField("item_title");

        SearchResult searchResult = searchDao.search(query);
        Long pageCount = searchResult.getRecordCount() / rows;
        if (searchResult.getRecordCount() % rows > 0) {
            pageCount++;
        }
        searchResult.setPageCount(pageCount);
        return searchResult;
    }
    @Override
    public TaotaoResult updateSearchItemById(Long itemId) throws Exception{
        return searchDao.updateSearchItemById(itemId);
    }
}
